package com.alibaba.otter.manager.web.dto;

import com.alibaba.otter.canal.instance.manager.model.CanalParameter;
import com.alibaba.otter.manager.web.common.NumberFormatUtil;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Getter
@Setter
@NoArgsConstructor
public class CanalParameterDTO extends CanalParameter {



    @JsonSetter("groupDbAddresses")
    public void setGroupDbAddress(String dbAddressesString) {

        if (StringUtils.isBlank(dbAddressesString)) {
            return;
        }
        // 解析格式：
        // 127.0.0.1:3306:MYSQL,127.0.0.1:3306:ORACLE;127.0.0.1:3306,127.0.0.1:3306;
        // 第一层的分号代表主备概念，,第二层逗号代表分组概念
        List<List<DataSourcing>> dbSocketAddress = new ArrayList<>();
        String[] dbAddresses = StringUtils.split(dbAddressesString, ";");

        for (String dbAddressString : dbAddresses) {
            List<CanalParameter.DataSourcing> groupDbSocketAddress = new ArrayList<>();
            String[] groupDbAddresses = StringUtils.split(dbAddressString, ",");
            for (String groupDbAddress : groupDbAddresses) {
                String[] dbUrl = StringUtils.split(groupDbAddress, ":");
                InetSocketAddress address = new InetSocketAddress(dbUrl[0].trim(), Integer.parseInt(dbUrl[1]));
                CanalParameter.SourcingType type = getSourcingType();
                if (dbUrl.length > 2) {
                    type = CanalParameter.SourcingType.valueOf(dbUrl[2]);
                }
                groupDbSocketAddress.add(new CanalParameter.DataSourcing(type, address));
            }
            dbSocketAddress.add(groupDbSocketAddress);
        }
        setGroupDbAddresses(dbSocketAddress);
    }

    @JsonGetter("groupDbAddresses")
    public String getGroupDbAddress() {
        return NumberFormatUtil.formatGroupDbAddress(getSourcingType(),getGroupDbAddresses());
    }


    @JsonSetter("zkClusters")
    public void setZkClusters(String zkClustersString){
        String[] zkClusters = StringUtils.split(zkClustersString, ";");
        setZkClusters(Arrays.asList(zkClusters));
    }

}
